<?php
$title_msg = 'Register new user account';
$header_msg = 'Account Registration';

require_once ('db.php');
include_once('header.inc');

if (!(empty($_POST['test_username']))) {

//	echo "<BR>username is not empty<BR>";
	$usrgrp;
	$sql = "select * FROM `users`";
	$usrget = $eebsdb->query($sql);
	if ($usrget->rowCount() === 1) {
		echo "<P>there are no previous users</P>";
		$usrgrp = 2;
	} else {
	$usrgrp = 1;
	}
	$sql = "SELECT `username` FROM `users` WHERE `username` LIKE '"
		. $_POST['test_username'] . "'";
	$usrget = $eebsdb->query($sql);
	$usrget->rowCount();

//	echo "<BR>check row count:<BR>";

	if ($usrget->rowCount() > 0) {
		echo "<P>username already taken, choose another username </P>";
	} else {
		if (!(empty($_POST['test_password']))
			&& $_POST['test_password'] === $_POST['test_re_password']) {

//			echo "<BR>password accepted<BR>";

			$newsalt = rand(111111111, 999999999);
			$newpass = md5(md5($_POST['test_password']) . md5($newsalt));

			$sql = 'INSERT INTO users (username, email, group_id, salt,
				passhash) VALUES (?, ?, ?, ?, ?)';
			$sth = $eebsdb->prepare($sql);
			if (!(empty($_POST['test_email']))) {

//				echo "<BR>email entered<BR>";

				$sth->execute(array ($_POST['test_username'],
					$_POST['test_email'], $usrgrp, $newsalt, $newpass))
					or die("database user insert query not successfull");
				$usrget = $eebsdb->query("SELECT * FROM `users` WHERE `username`='"
					.$_POST['test_username']."'");
				$usrarr = $usrget->fetch();
				$_SESSION['USER_ID'] = $usrarr['id'];
				$_SESSION['USERNAME'] = $usrarr['username'];
				$_SESSION['USERGRP'] = $usrarr['group_id'];
				$_POST['register_login'] = 1;

//				echo "<BR>redirecting<BR>";

				Header('Location: ./index.php');
?>
<!--
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<P>
	Success, your user has been created and logged in.
</P>
</body>
</html>
-->
<?php
			} else {
				echo "<P>email is empty</P>";
			}
		} else {
			echo "<P>password is empty or does not match</P>";
		}
	}
exit ();
}
include_once('header.inc');
?>
<!-- add a password comparison form and check
	pwd === pwdcmp -->
	<form method="post" action="reg.php">
		<label for="test_username">Username: </label>
			<input type="text" name="test_username" title="usr-really?"><br/>
		<label for="test_password">Password: </label>
			<input type="password" name="test_password" title="pwd-really?"><br/>
		<label for="test_re_password">Re-type password: </label>
			<input type="password" name="test_re_password" title="repwd-really="><br/>
		<label for="test_email">E-mail: </label>
			<input type="email" name="test_email" title="email-really?"><br/>
		<input type="submit" value="throw data into script masher"/>
	</form>
<?php include_once('footer.inc'); ?>
